import QtQuick
import QtQuick.Controls.FluentWinUI3
import QtQuick.Layouts
import QtPositioning
import QtLocation

import GPSTools

/**
 * 主应用程序窗口 - 使用FluentWinUI3样式
 * 提供现代化的Windows 11风格界面
 */
ApplicationWindow {
    id: window
    width: 1000
    height: 650
    visible: true
    title: qsTr("GPS工具 - NMEA-0183解析器")

    // 设置FluentWinUI3样式的调色板
    palette.accent: "#0078d4"
    palette.base: "#ffffff"
    palette.window: "#f3f3f3"

    property alias gpsController: gpsController

    /**
     * GPS控制器实例
     */
    GpsController {
        id: gpsController
    }

    /**
     * 主内容区域 - 使用正确的FluentWinUI3布局
     */
    RowLayout {
        anchors.fill: parent
        anchors.margins: 16

        ColumnLayout {
            Layout.fillHeight: true
            spacing: 16

            /**
             * 连接状态卡片 - FluentWinUI3样式
             */
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 50
                color: gpsController.isConnected ? "#e8f5e8" : "#fff3cd"
                border.color: gpsController.isConnected ? "#28a745" : "#ffc107"
                border.width: 2
                radius: 8

                RowLayout {
                    anchors.fill: parent

                    Item {
                        Layout.alignment: Qt.AlignLeft
                        Layout.leftMargin: 50

                        Rectangle {
                            anchors.centerIn: parent
                            width: 35
                            height: 35
                            radius: 18
                            color: gpsController.isConnected ? "#28a745" : "#6c757d"

                            SequentialAnimation on scale {
                                running: gpsController.isConnected && gpsController.isValid
                                loops: Animation.Infinite
                                NumberAnimation { to: 1.1; duration: 1000; easing.type: Easing.InOutQuad }
                                NumberAnimation { to: 1.0; duration: 1000; easing.type: Easing.InOutQuad }
                            }
                        }
                    }

                    ColumnLayout {
                        Layout.alignment: Qt.AlignLeft
                        spacing: 4

                        Label {
                            text: gpsController.isConnected ? "GPS已连接" : "GPS未连接"
                            font.pixelSize: 16
                            font.bold: true
                            color: gpsController.isConnected ? "#28a745" : "#6c757d"
                        }

                        Label {
                            text: gpsController.isConnected ?
                                      (gpsController.isValid ? "定位有效 - " + gpsController.currentPort : "等待GPS信号 - " + gpsController.currentPort) :
                                      gpsController.statusMessage
                            font.pixelSize: 12
                            color: "#6c757d"
                        }
                    }

                    Label {
                        Layout.alignment: Qt.AlignRight
                        Layout.rightMargin: 50

                        text: gpsController.isConnected ? "接收: " + gpsController.receivedMessages : "无数据连接"
                        font.pixelSize: 12
                        color: "#6c757d"
                    }
                }
            }

            /**
             * 串口配置卡片 - FluentWinUI3样式
             */
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: 140
                color: "#ffffff"
                border.color: "#e5e5e5"
                border.width: 1
                radius: 8

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: 16
                    spacing: 12

                    Label {
                        text: "串口配置"
                        font.pixelSize: 16
                        font.bold: true
                        color: "#323130"
                    }

                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 12

                        ColumnLayout {
                            Layout.fillWidth: true
                            spacing: 6

                            Label {
                                text: "串口设备"
                                font.pixelSize: 12
                                color: "#605e5c"
                            }

                            ComboBox {
                                id: portComboBox
                                Layout.fillWidth: true
                                Layout.preferredHeight: 32
                                model: gpsController.availablePorts
                                enabled: !gpsController.isConnected
                                displayText: currentIndex >= 0 ? currentText : "选择串口..."

                                // 设置ComboBox样式确保可见
                                background: Rectangle {
                                    color: enabled ? "#ffffff" : "#f3f2f1"
                                    border.color: "#605e5c"
                                    border.width: 1
                                    radius: 4
                                }

                                contentItem: Text {
                                    leftPadding: 8
                                    rightPadding: portComboBox.indicator.width + portComboBox.spacing
                                    text: portComboBox.displayText
                                    font: portComboBox.font
                                    color: enabled ? "#323130" : "#a19f9d"
                                    verticalAlignment: Text.AlignVCenter
                                    elide: Text.ElideRight
                                }

                                // 设置下拉列表样式
                                popup: Popup {
                                    y: portComboBox.height - 1
                                    width: portComboBox.width
                                    implicitHeight: contentItem.implicitHeight
                                    padding: 1

                                    contentItem: ListView {
                                        clip: true
                                        implicitHeight: contentHeight
                                        model: portComboBox.popup.visible ? portComboBox.delegateModel : null
                                        currentIndex: portComboBox.highlightedIndex

                                        ScrollIndicator.vertical: ScrollIndicator { }
                                    }

                                    background: Rectangle {
                                        color: "#ffffff"
                                        border.color: "#605e5c"
                                        border.width: 1
                                        radius: 4
                                    }
                                }

                                delegate: ItemDelegate {
                                    width: portComboBox.width
                                    contentItem: Text {
                                        text: modelData
                                        color: "#323130"
                                        font: portComboBox.font
                                        elide: Text.ElideRight
                                        verticalAlignment: Text.AlignVCenter
                                    }
                                    background: Rectangle {
                                        color: parent.hovered ? "#f3f2f1" : "transparent"
                                    }
                                    highlighted: portComboBox.highlightedIndex === index
                                }

                                indicator: Canvas {
                                    id: canvas
                                    x: portComboBox.width - width - portComboBox.rightPadding
                                    y: portComboBox.topPadding + (portComboBox.availableHeight - height) / 2
                                    width: 12
                                    height: 8
                                    contextType: "2d"

                                    Connections {
                                        target: portComboBox
                                        function onPressedChanged() { canvas.requestPaint(); }
                                    }

                                    onPaint: {
                                        context.reset();
                                        context.moveTo(0, 0);
                                        context.lineTo(width, 0);
                                        context.lineTo(width / 2, height);
                                        context.closePath();
                                        context.fillStyle = portComboBox.pressed ? "#323130" : "#605e5c";
                                        context.fill();
                                    }
                                }

                                onActivated: {
                                    if (currentIndex >= 0) {
                                        console.log("选择串口:", currentText)
                                    }
                                }
                            }
                        }

                        ColumnLayout {
                            Layout.preferredWidth: 120
                            spacing: 6

                            Label {
                                text: "波特率"
                                font.pixelSize: 12
                                color: "#605e5c"
                            }

                            ComboBox {
                                id: baudRateComboBox
                                Layout.fillWidth: true
                                Layout.preferredHeight: 32
                                model: ["9600", "19200", "38400", "57600", "115200"]
                                currentIndex: 4
                                enabled: !gpsController.isConnected

                                // 设置ComboBox样式确保可见
                                background: Rectangle {
                                    color: enabled ? "#ffffff" : "#f3f2f1"
                                    border.color: "#605e5c"
                                    border.width: 1
                                    radius: 4
                                }

                                contentItem: Text {
                                    leftPadding: 8
                                    rightPadding: baudRateComboBox.indicator.width + baudRateComboBox.spacing
                                    text: baudRateComboBox.displayText
                                    font: baudRateComboBox.font
                                    color: enabled ? "#323130" : "#a19f9d"
                                    verticalAlignment: Text.AlignVCenter
                                    elide: Text.ElideRight
                                }

                                // 设置下拉列表样式
                                popup: Popup {
                                    y: baudRateComboBox.height - 1
                                    width: baudRateComboBox.width
                                    implicitHeight: contentItem.implicitHeight
                                    padding: 1

                                    contentItem: ListView {
                                        clip: true
                                        implicitHeight: contentHeight
                                        model: baudRateComboBox.popup.visible ? baudRateComboBox.delegateModel : null
                                        currentIndex: baudRateComboBox.highlightedIndex

                                        ScrollIndicator.vertical: ScrollIndicator { }
                                    }

                                    background: Rectangle {
                                        color: "#ffffff"
                                        border.color: "#605e5c"
                                        border.width: 1
                                        radius: 4
                                    }
                                }

                                delegate: ItemDelegate {
                                    width: baudRateComboBox.width
                                    contentItem: Text {
                                        text: modelData
                                        color: "#323130"
                                        font: baudRateComboBox.font
                                        elide: Text.ElideRight
                                        verticalAlignment: Text.AlignVCenter
                                    }
                                    background: Rectangle {
                                        color: parent.hovered ? "#f3f2f1" : "transparent"
                                    }
                                    highlighted: baudRateComboBox.highlightedIndex === index
                                }

                                indicator: Canvas {
                                    id: baudCanvas
                                    x: baudRateComboBox.width - width - baudRateComboBox.rightPadding
                                    y: baudRateComboBox.topPadding + (baudRateComboBox.availableHeight - height) / 2
                                    width: 12
                                    height: 8
                                    contextType: "2d"

                                    Connections {
                                        target: baudRateComboBox
                                        function onPressedChanged() { baudCanvas.requestPaint(); }
                                    }

                                    onPaint: {
                                        context.reset();
                                        context.moveTo(0, 0);
                                        context.lineTo(width, 0);
                                        context.lineTo(width / 2, height);
                                        context.closePath();
                                        context.fillStyle = baudRateComboBox.pressed ? "#323130" : "#605e5c";
                                        context.fill();
                                    }
                                }

                                onActivated: {
                                    gpsController.baudRate = parseInt(currentText)
                                }
                            }
                        }

                        Button {
                            id: connectButton
                            Layout.preferredWidth: 80
                            Layout.preferredHeight: 32
                            text: gpsController.isConnected ? "断开" : "连接"

                            // 设置Button样式确保可见
                            background: Rectangle {
                                color: parent.pressed ? "#005a9e" : (parent.hovered ? "#106ebe" : "#0078d4")
                                border.color: "#005a9e"
                                border.width: 1
                                radius: 4
                            }

                            contentItem: Text {
                                text: parent.text
                                font: parent.font
                                color: "#ffffff"
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }

                            onClicked: {
                                if (gpsController.isConnected) {
                                    gpsController.disconnectPort()
                                } else {
                                    if (portComboBox.currentIndex >= 0) {
                                        var portName = portComboBox.currentText
                                        var baudRate = parseInt(baudRateComboBox.currentText)
                                        gpsController.connectToPort(portName, baudRate)
                                    }
                                }
                            }
                        }

                        Button {
                            Layout.preferredWidth: 60
                            Layout.preferredHeight: 32
                            text: "刷新"
                            enabled: !gpsController.isConnected

                            // 设置Button样式确保可见
                            background: Rectangle {
                                color: enabled ? (parent.pressed ? "#005a9e" : (parent.hovered ? "#106ebe" : "#0078d4")) : "#f3f2f1"
                                border.color: enabled ? "#005a9e" : "#a19f9d"
                                border.width: 1
                                radius: 4
                            }

                            contentItem: Text {
                                text: parent.text
                                font: parent.font
                                color: enabled ? "#ffffff" : "#a19f9d"
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }

                            onClicked: {
                                gpsController.refreshPorts()
                            }
                        }
                    }
                }
            }

            /**
             * GPS数据显示区域 - FluentWinUI3样式
             */
            Rectangle {
                Layout.fillWidth: true
                Layout.preferredHeight: dataGrid.implicitHeight + 32  // 设置固定高度而不是fillHeight
                color: "#ffffff"
                border.color: "#e5e5e5"
                border.width: 1
                radius: 8

                ColumnLayout {
                    id: dataGrid
                    anchors.fill: parent
                    anchors.margins: 16
                    spacing: 12

                    Label {
                        text: "GPS数据"
                        font.pixelSize: 16
                        font.bold: true
                        color: "#323130"
                    }

                    GridLayout {
                        Layout.fillWidth: true
                        columns: 2
                        columnSpacing: 16
                        rowSpacing: 12

                        // 位置信息卡片
                        Rectangle {
                            Layout.fillWidth: true
                            Layout.preferredHeight: 100
                            color: "#f8f9fa"
                            border.color: "#e5e5e5"
                            border.width: 1
                            radius: 6

                            ColumnLayout {
                                anchors.fill: parent
                                anchors.margins: 12
                                spacing: 8

                                Label {
                                    text: "位置信息"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#323130"
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 16

                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 4

                                        Label {
                                            text: "纬度"
                                            font.pixelSize: 11
                                            color: "#605e5c"
                                        }
                                        Label {
                                            text: gpsController.latitude.toFixed(6) + "°"
                                            font.family: "Consolas, Monaco, monospace"
                                            font.pixelSize: 15
                                            font.bold: true
                                            color: "#323130"
                                        }
                                    }

                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 4

                                        Label {
                                            text: "经度"
                                            font.pixelSize: 11
                                            color: "#605e5c"
                                        }
                                        Label {
                                            text: gpsController.longitude.toFixed(6) + "°"
                                            font.family: "Consolas, Monaco, monospace"
                                            font.pixelSize: 15
                                            font.bold: true
                                            color: "#323130"
                                        }
                                    }
                                }
                            }
                        }

                        // 海拔信息卡片
                        Rectangle {
                            Layout.fillWidth: true
                            Layout.preferredHeight: 100
                            color: "#f8f9fa"
                            border.color: "#e5e5e5"
                            border.width: 1
                            radius: 6

                            ColumnLayout {
                                anchors.fill: parent
                                anchors.margins: 12
                                spacing: 8

                                Label {
                                    text: "海拔高度"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#323130"
                                }

                                Label {
                                    text: gpsController.altitude.toFixed(1) + " 米"
                                    font.family: "Consolas, Monaco, monospace"
                                    font.pixelSize: 18
                                    font.bold: true
                                    color: "#0078d4"
                                    Layout.alignment: Qt.AlignCenter
                                }
                            }
                        }

                        // 运动信息卡片
                        Rectangle {
                            Layout.fillWidth: true
                            Layout.preferredHeight: 100
                            color: "#f8f9fa"
                            border.color: "#e5e5e5"
                            border.width: 1
                            radius: 6

                            ColumnLayout {
                                anchors.fill: parent
                                anchors.margins: 12
                                spacing: 8

                                Label {
                                    text: "运动信息"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#323130"
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 16

                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 4

                                        Label {
                                            text: "速度"
                                            font.pixelSize: 11
                                            color: "#605e5c"
                                        }
                                        Label {
                                            text: gpsController.getSpeedKmh().toFixed(1) + " km/h"
                                            font.family: "Consolas, Monaco, monospace"
                                            font.pixelSize: 18
                                            font.bold: true
                                            color: "#107c10"
                                        }
                                    }

                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 4

                                        Label {
                                            text: "航向"
                                            font.pixelSize: 11
                                            color: "#605e5c"
                                        }
                                        Label {
                                            text: gpsController.course.toFixed(1) + "°"
                                            font.family: "Consolas, Monaco, monospace"
                                            font.pixelSize: 18
                                            font.bold: true
                                            color: "#107c10"
                                        }
                                    }
                                }
                            }
                        }

                        // 卫星信息卡片
                        Rectangle {
                            Layout.fillWidth: true
                            Layout.preferredHeight: 100
                            color: "#f8f9fa"
                            border.color: "#e5e5e5"
                            border.width: 1
                            radius: 6

                            ColumnLayout {
                                anchors.fill: parent
                                anchors.margins: 12
                                spacing: 8

                                Label {
                                    text: "卫星信息"
                                    font.pixelSize: 14
                                    font.bold: true
                                    color: "#323130"
                                }

                                RowLayout {
                                    Layout.fillWidth: true
                                    spacing: 16

                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 4

                                        Label {
                                            text: "卫星数量"
                                            font.pixelSize: 11
                                            color: "#605e5c"
                                        }
                                        Label {
                                            text: gpsController.satellites.toString()
                                            font.family: "Consolas, Monaco, monospace"
                                            font.pixelSize: 18
                                            font.bold: true
                                            color: "#d83b01"
                                        }
                                    }

                                    ColumnLayout {
                                        Layout.fillWidth: true
                                        spacing: 4

                                        Label {
                                            text: "定位质量"
                                            font.pixelSize: 11
                                            color: "#605e5c"
                                        }
                                        Label {
                                            text: gpsController.quality
                                            font.family: "Consolas, Monaco, monospace"
                                            font.pixelSize: 18
                                            font.bold: true
                                            color: "#8764b8"
                                        }
                                    }
                                }
                            }
                        }

                        // 时间和状态信息卡片
                        Rectangle {
                            Layout.columnSpan: 2
                            Layout.fillWidth: true
                            Layout.preferredHeight: 80
                            color: "#f3f2f1"
                            border.color: "#d2d0ce"
                            border.width: 1
                            radius: 6

                            RowLayout {
                                anchors.fill: parent
                                anchors.margins: 12
                                spacing: 20

                                ColumnLayout {
                                    Layout.fillWidth: true
                                    spacing: 4

                                    Label {
                                        text: "时间戳"
                                        font.pixelSize: 12
                                        color: "#605e5c"
                                    }
                                    Label {
                                        text: gpsController.timestamp
                                        font.family: "Consolas, Monaco, monospace"
                                        font.pixelSize: 18
                                        font.bold: true
                                        color: "#323130"
                                    }
                                }

                                ColumnLayout {
                                    Layout.fillWidth: true
                                    spacing: 4

                                    Label {
                                        text: "状态信息"
                                        font.pixelSize: 12
                                        color: "#605e5c"
                                    }
                                    Label {
                                        text: gpsController.statusMessage
                                        font.pixelSize: 18
                                        color: "#323130"
                                        wrapMode: Text.WordWrap
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        /**
         * 地图显示区域
         */
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "#ffffff"
            border.color: "#e5e5e5"
            border.width: 1
            radius: 8

            ColumnLayout {
                id: mapGrid
                anchors.fill: parent
                anchors.margins: 16
                spacing: 12

                Label {
                    text: "地图显示"
                    font.pixelSize: 16
                    font.bold: true
                    color: "#323130"
                }

                Map {
                    property var curCoord: QtPositioning.coordinate(gpsController.latitude.toFixed(6), gpsController.longitude.toFixed(6))
                    id: map
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    plugin: Plugin {
                        id: myPlugin
                        name: "osm"
                        // 配置OSM地图服务参数
                        PluginParameter {
                            name: "osm.useragent"
                            value: "GPSTools/1.0"
                        }
                        PluginParameter {
                            name: "osm.mapping.host"
                            value: "https://tile.openstreetmap.org/"
                        }
                        PluginParameter {
                            name: "osm.mapping.copyright"
                            value: "© OpenStreetMap contributors"
                        }
                        PluginParameter {
                            name: "osm.mapping.providersrepository.disabled"
                            value: "true"
                        }
                    }
                    zoomLevel: (gpsController.isValid && (gpsController.latitude !== 0.0 || gpsController.longitude !== 0.0)) ? 13 : 1
                    center: (gpsController.isValid && (gpsController.latitude !== 0.0 || gpsController.longitude !== 0.0)) ? curCoord : QtPositioning.coordinate(0.0, 0.0)
                    
                    MouseArea {
                        anchors.fill: parent
                        acceptedButtons: Qt.LeftButton | Qt.RightButton
                        property var lastPanPoint
                        property bool isPanning: false
                        onPressed: function(mouse) {
                            lastPanPoint = Qt.point(mouse.x, mouse.y)
                            isPanning = true
                        }
                        onPositionChanged: function(mouse) {
                            if (isPanning && pressed) {
                                var dx = mouse.x - lastPanPoint.x
                                var dy = mouse.y - lastPanPoint.y
                                map.pan(-dx, -dy)
                                lastPanPoint = Qt.point(mouse.x, mouse.y)
                            }
                        }
                        onReleased: function(mouse) {
                            isPanning = false
                        }
                        onWheel: function(wheel) {
                            var zoomChange = wheel.angleDelta.y > 0 ? 1 : -1
                            map.zoomLevel = Math.max(1, Math.min(20, map.zoomLevel + zoomChange))
                        }
                    }
                    
                    MapQuickItem {
                        id: positionMarker
                        coordinate: parent.curCoord
                        visible: gpsController.isValid && (gpsController.latitude !== 0.0 || gpsController.longitude !== 0.0)
                        anchorPoint: Qt.point(sourceItem.width/2, sourceItem.height/2)
                        zoomLevel: 0
                        
                        sourceItem: Rectangle {
                            width: 20
                            height: 20
                            radius: 15
                            color: "#ff4444"
                            border.color: "#ffffff"
                            border.width: 3
                            // 阴影效果
                            Rectangle {
                                anchors.centerIn: parent
                                width: parent.width + 6
                                height: parent.height + 6
                                radius: (parent.width + 6) / 2
                                color: "transparent"
                                border.color: "#ff4444"
                                border.width: 1
                                opacity: 0.3
                            }
                            
                            // 中心点
                            Rectangle {
                                anchors.centerIn: parent
                                width: 8
                                height: 8
                                radius: 4
                                color: "#ffffff"
                            }
                            
                            MouseArea {
                                anchors.fill: parent
                                onClicked: {
                                    console.log(gpsController.latitude, gpsController.longitude)
                                }
                            }
                        }
                    }
                    
                    /**
                     * 位置精度圆圈
                     */
                    MapCircle {
                        id: accuracyCircle
                        center: parent.curCoord
                        radius: 100  // 精度半径（米）
                        visible: gpsController.isValid && (gpsController.latitude !== 0.0 || gpsController.longitude !== 0.0)
                        color: "#ff4444"
                        border.color: "#ff4444"
                        border.width: 2
                        opacity: 0.15
                    }
                }
            }
        }
    }

    /**
    * 连接状态变化处理
    */
    Connections {
        target: gpsController
        function onErrorOccurred(error) {
            console.log("错误:", error)
        }
    }

    /**
     * 应用启动时的初始化
     */
    Component.onCompleted: {
        // 延迟一小段时间后尝试自动连接，确保UI完全加载
        autoConnectTimer.start()
    }

    /**
     * 自动连接定时器
     */
    Timer {
        id: autoConnectTimer
        interval: 1000  // 1秒延迟
        repeat: false
        onTriggered: {
            console.log("尝试自动连接到上次成功的串口...")
            var success = gpsController.autoConnectToLastPort()
            if (success) {
                console.log("自动连接成功")
            } else {
                console.log("自动连接失败或没有保存的串口信息")
            }
        }
    }
}
